#!/usr/bin/python
#-*- coding:utf-8 -*-

# guisupport.py
#
# Copyright (c) 2007 Marcelo Lira dos Santos
#
# Author: Marcelo Lira dos Santos <setanta@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import pygtk
pygtk.require('2.0')
import gtk
import pango
from os.path import join

import core
from data import *
from value_bar import ValueBar

(
SKILLS_COL_ID,
SKILLS_COL_NAME_GROUP,
SKILLS_COL_COST,
SKILLS_COL_LEVEL,
SKILLS_COL_BONUS,
SKILLS_COL_TOTAL,
SKILLS_COL_HAS_SPEC,
SKILLS_COL_IS_SKILL,
SKILLS_COL_UNKNOWN,
SKILLS_COL_FGCOLOR,
SKILLS_COL_BGCOLOR
) = xrange(11)

(
SPECSUGGEST_COL_SKILL_ID,
SPECSUGGEST_COL_NAME
) = xrange(2)

(
SPELLS_COL_ID,
SPELLS_COL_GROUP_ID,
SPELLS_COL_NAME_GROUP,
SPELLS_COL_COST,
SPELLS_COL_LEVEL,
SPELLS_COL_TOOLTIP,
SPELLS_COL_IS_SPELL,
SPELLS_COL_UNKNOWN,
SPELLS_COL_FGCOLOR
) = xrange(9)

(
EQUIP_COL_ID,
EQUIP_COL_NAME_GROUP,
EQUIP_COL_DESC,
EQUIP_COL_PRICE,
EQUIP_COL_PRICE_STR,
EQUIP_COL_QTD,
EQUIP_COL_IS_ITEM,
EQUIP_COL_NOTMINE,
EQUIP_COL_FGCOLOR
) = xrange(9)

(
PERSONA_COL_ID,
PERSONA_COL_NAME,
PERSONA_COL_RACE_ID,
PERSONA_COL_LEVEL,
PERSONA_COL_TOOLTIP,
PERSONA_COL_PIXBUF
) = xrange(6)

(
GOD_COL_ID,
GOD_COL_NAME,
GOD_COL_REALM
) = xrange(3)

FG_COLOR = gtk.gdk.color_parse('#CCC')
BG_COLOR = {True  : gtk.gdk.color_parse('#AAA'),
            False : gtk.gdk.color_parse('#EEE')}
COLOR_BLACK = gtk.gdk.color_parse('#000')
COLOR_WHITE = gtk.gdk.color_parse('#FFF')

def init_gods(combo, gods=[]):
    model = gtk.ListStore(int, str)
    cell = gtk.CellRendererText()
    combo.set_model(model)
    combo.pack_start(cell, True)
    combo.add_attribute(cell, 'markup', 1)
    for god in gods:
        model.append([god[0], '<b>%s</b> (%s)' % (god[1], god[2])])

    return model


#TODO: mudar todos os metodos init para receber um objeto Store, em lugar de listas.
def init_players_names(completion, players=[]):
    model = gtk.ListStore(str)
    completion.set_model(model)
    completion.set_text_column(0)
    for player in players:
        model.append([player])

    return model


def init_personas(treeview, store, pixbufspath, gtk_ok=False):
    model = gtk.ListStore(int, str, int, int, str, gtk.gdk.Pixbuf)
    treeview.set_model(model)
    treeview.set_search_column(PERSONA_COL_NAME)
    if gtk_ok:
        treeview.set_tooltip_column(PERSONA_COL_TOOLTIP)

    column = gtk.TreeViewColumn('', gtk.CellRendererPixbuf(),
                                pixbuf=PERSONA_COL_PIXBUF)
    column.set_expand(False)
    treeview.append_column(column)

    column = gtk.TreeViewColumn('Personagem', gtk.CellRendererText(),
                                text=PERSONA_COL_NAME)
    column.set_expand(True)
    column.set_sort_column_id(PERSONA_COL_NAME)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Nível', renderer,
                                text=PERSONA_COL_LEVEL)
    column.set_expand(False)
    column.set_sort_column_id(PERSONA_COL_LEVEL)
    treeview.append_column(column)

    PROFESSION_PIXBUFS = [
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'warrior.png')),
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'thief.png')),
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'priest.png')),
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'mage.png')),
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'ranger.png')),
        gtk.gdk.pixbuf_new_from_file(join(pixbufspath, 'bard.png'))
    ]

    for p_id, p_name, p_race, p_prof, p_level in store.get_persona_list():
        race_name = store.get_race_name(p_race)
        prof_name = store.get_profession_name(p_prof)
        tooltip = '<big><b>%s</b></big>\n%s, %s, nvl %d' % \
                  (p_name, race_name, prof_name, p_level)
        model.append([p_id, p_name, p_race, p_level, tooltip,
                      PROFESSION_PIXBUFS[p_prof-1]])

    return model


def init_skills(treeview, store):
    # [id, name_group, cost, level, bonus_attribute,
    #  total, has_spec, visible, unknown, fgcolor, bgcolor]
    model = gtk.TreeStore(int, str, int, int, str, int, bool,
                          bool, bool, gtk.gdk.Color, gtk.gdk.Color)
    _filter = model.filter_new()
    treeview.set_model(_filter)

    def do_add_skill(parent_iter, skill_id, skill_name, cost, bonus, has_spec):
        model.append(parent_iter, [skill_id, skill_name, cost, 0,
                                   ATTRIBUTE_SHORT_NAMES[bonus], 0,
                                   bool(has_spec), True, True, FG_COLOR,
                                   COLOR_WHITE])

    def do_add_group(parent_iter, group_id, group_name):
        if parent_iter is None:
            name = '<b>%s</b>' % group_name
        else:
            name = '<i>%s</i>' % group_name
        return model.append(parent_iter, [group_id, name, 0, 0, None,
                                          0, False, False, False, FG_COLOR,
                                          BG_COLOR[parent_iter is None]])

    parents = store.get_skill_group_parents()
    for group_id, group_name in parents:
        iter = do_add_group(None, group_id, group_name)

        skills = store.get_skills_from_group(group_id)
        for skill_id, skill_name, cost, bonus, has_spec in skills:
            if has_spec:
                name = '%s ...' % skill_name
            else:
                name = skill_name
            do_add_skill(iter, skill_id, name, cost, bonus, has_spec)

        subgroups = store.get_skill_group_children(group_id)
        for subgroup_id, subgroup_name in subgroups:
            iter2 = do_add_group(iter, subgroup_id, subgroup_name)

            skills = store.get_skills_from_group(subgroup_id)
            for skill_id, skill_name, cost, bonus, has_spec in skills:
                if has_spec:
                    name = '%s ...' % skill_name
                else:
                    name = skill_name
                do_add_skill(iter2, skill_id, name, cost, bonus, has_spec)

    renderer = gtk.CellRendererText()
    column = gtk.TreeViewColumn('Habilidade', renderer,
                                markup=SKILLS_COL_NAME_GROUP)
    column.add_attribute(renderer, 'cell-background-gdk', SKILLS_COL_BGCOLOR)
    column.add_attribute(renderer, 'foreground-set', SKILLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SKILLS_COL_FGCOLOR)
    column.set_expand(True)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Custo', renderer, text=SKILLS_COL_COST)
    column.add_attribute(renderer, 'visible', SKILLS_COL_IS_SKILL)
    column.add_attribute(renderer, 'cell-background-gdk', SKILLS_COL_BGCOLOR)
    column.add_attribute(renderer, 'foreground-set', SKILLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SKILLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Nível', renderer, text=SKILLS_COL_LEVEL)
    column.add_attribute(renderer, 'visible', SKILLS_COL_IS_SKILL)
    column.add_attribute(renderer, 'cell-background-gdk', SKILLS_COL_BGCOLOR)
    column.add_attribute(renderer, 'foreground-set', SKILLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SKILLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Ajuste', renderer, text=SKILLS_COL_BONUS)
    column.add_attribute(renderer, 'visible', SKILLS_COL_IS_SKILL)
    column.add_attribute(renderer, 'cell-background-gdk', SKILLS_COL_BGCOLOR)
    column.add_attribute(renderer, 'foreground-set', SKILLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SKILLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Total', renderer, text=SKILLS_COL_TOTAL)
    column.add_attribute(renderer, 'visible', SKILLS_COL_IS_SKILL)
    column.add_attribute(renderer, 'cell-background-gdk', SKILLS_COL_BGCOLOR)
    column.add_attribute(renderer, 'foreground-set', SKILLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SKILLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    treeview.expand_all()

    return model, _filter

def init_specializations(comboentry, completion, store):
    specs = store.get_skill_specialization_suggestions()
    # (skill_id, specialization)
    model = gtk.ListStore(int, str)
    _filter = model.filter_new()

    comboentry.set_model(_filter)
    comboentry.set_text_column(SPECSUGGEST_COL_NAME)

    completion.set_model(_filter)
    completion.set_text_column(SPECSUGGEST_COL_NAME)
    comboentry.child.set_completion(completion)

    for spec in specs:
        model.append(spec)

    return model, _filter


def init_spells(treeview, store, gtk_ok=False):
    # [id, group_id, group_or_name, cost, level,
    #  tooltip, visible, unknown, fgcolor]
    model = gtk.TreeStore(int, int, str, int, int, str,
                          bool, bool, gtk.gdk.Color)
    _filter = model.filter_new()
    treeview.set_model(_filter)

    def do_add_spell(parent_iter, spell_id, group_id, spell, cost):
        if spell.description is None:
            tooltip = None
        else:
            tooltip = '<big><b>%s</b></big>\n<b>Evocação:</b> %s\n' \
                      '<b>Alcance:</b> %s\n<b>Duração:</b> %s\n%s' % \
                      (spell.name, spell.evocation, spell.range,
                       spell.duration, spell.description)
        model.append(parent_iter, [spell_id, group_id, spell.name, cost,
                                   0, tooltip, True, True, FG_COLOR])

    def do_add_group(parent_iter, group_id, group_name):
        if parent_iter is None:
            name = '<b>%s</b>' % group_name
        else:
            name = '<i>%s</i>' % group_name
        return model.append(parent_iter, [-1, group_id, name,
                                          0, 0, None, False, False,
                                          COLOR_BLACK])

    parents = store.get_spell_group_parents()
    for group_id, group_name in parents:
        iter = do_add_group(None, group_id, group_name)

        for spell_id, spell, cost in store.get_spells_from_group(group_id):
            do_add_spell(iter, spell_id, group_id, spell, cost)

        subgroups = store.get_spell_group_children(group_id)
        for subgroup_id, subgroup_name in subgroups:
            iter2 = do_add_group(iter, subgroup_id, subgroup_name)
            for spell_id, spell, cost in store.get_spells_from_group(subgroup_id):
                do_add_spell(iter2, spell_id, subgroup_id, spell, cost)


    renderer = gtk.CellRendererText()
    column = gtk.TreeViewColumn('Magia', renderer,
                                markup=SPELLS_COL_NAME_GROUP)
    column.add_attribute(renderer, 'foreground-set', SPELLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SPELLS_COL_FGCOLOR)
    column.set_expand(True)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Custo', renderer, text=SPELLS_COL_COST)
    column.add_attribute(renderer, 'visible', SPELLS_COL_IS_SPELL)
    column.add_attribute(renderer, 'foreground-set', SPELLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SPELLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Nível', renderer, text=SPELLS_COL_LEVEL)
    column.add_attribute(renderer, 'visible', SPELLS_COL_IS_SPELL)
    column.add_attribute(renderer, 'foreground-set', SPELLS_COL_UNKNOWN)
    column.add_attribute(renderer, 'foreground-gdk', SPELLS_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    if gtk_ok:
        treeview.set_tooltip_column(SPELLS_COL_TOOLTIP)
    treeview.expand_all()

    return model, _filter


def init_equipment(treeview, store, gtk_ok=False):
    # [id, group_or_name, desc, price, price_str, qtd, visible, notmine, FG_COLOR]
    model = gtk.TreeStore(int, str, str, int, str, int, bool, bool, gtk.gdk.Color)
    _filter = model.filter_new()
    treeview.set_model(_filter)

    groups = store.get_equipment_groups()
    for group_id, group_name in groups:
        iter = model.append(None, [group_id, '<b>%s</b>' % group_name,
                                   None, 0, '', 0, False, False,
                                   COLOR_BLACK])

        equipment = store.get_equipment_from_group(group_id)
        for item_id, item_name, desc, price in equipment:
            model.append(iter, [item_id, item_name, desc,
                                price, core.format_money(price),
                                0, True, True, FG_COLOR])

    renderer = gtk.CellRendererText()
    column = gtk.TreeViewColumn('Equipamento', renderer,
                                markup=EQUIP_COL_NAME_GROUP)
    column.add_attribute(renderer, 'foreground-set', EQUIP_COL_NOTMINE)
    column.add_attribute(renderer, 'foreground-gdk', EQUIP_COL_FGCOLOR)
    column.set_expand(True)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 1.0)
    column = gtk.TreeViewColumn('Preço', renderer, text=EQUIP_COL_PRICE_STR)
    column.add_attribute(renderer, 'visible', EQUIP_COL_IS_ITEM)
    column.add_attribute(renderer, 'foreground-set', EQUIP_COL_NOTMINE)
    column.add_attribute(renderer, 'foreground-gdk', EQUIP_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    renderer = gtk.CellRendererText()
    renderer.set_property('xalign', 0.5)
    column = gtk.TreeViewColumn('Qtd', renderer, text=EQUIP_COL_QTD)
    column.add_attribute(renderer, 'visible', EQUIP_COL_IS_ITEM)
    column.add_attribute(renderer, 'foreground-set', EQUIP_COL_NOTMINE)
    column.add_attribute(renderer, 'foreground-gdk', EQUIP_COL_FGCOLOR)
    column.set_expand(False)
    treeview.append_column(column)

    if gtk_ok:
        treeview.set_tooltip_column(EQUIP_COL_DESC)
    treeview.expand_all()

    return model, _filter


def init_weapons(treeview):
    model = gtk.ListStore(str, str, int, int, int, int, int)
    treeview.set_model(model)
    column = gtk.TreeViewColumn('Nome', gtk.CellRendererText(), text=0)
    column.set_expand(True)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Habilidade', gtk.CellRendererText(), text=1)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Nível', gtk.CellRendererText(), text=2)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('L0', gtk.CellRendererText(), text=3)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('M0', gtk.CellRendererText(), text=4)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('P0', gtk.CellRendererText(), text=5)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Dano Máx.', gtk.CellRendererText(), text=6)
    column.set_expand(False)
    treeview.append_column(column)

    return model

def init_defence(treeview):
    model = gtk.ListStore(str, str, int, int)
    treeview.set_model(model)
    column = gtk.TreeViewColumn('Nome', gtk.CellRendererText(), text=0)
    column.set_expand(True)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Tipo', gtk.CellRendererText(), text=1)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Defesa Base', gtk.CellRendererText(), text=2)
    column.set_expand(False)
    treeview.append_column(column)
    column = gtk.TreeViewColumn('Absorção', gtk.CellRendererText(), text=3)
    column.set_expand(False)
    treeview.append_column(column)

    return model


# inicializa barras de valores -----------------------------------------------
def init_skills_value_bars(table):
    skill_pts = ValueBar(16, False)
    skill_pts.set_property('value', 2)

    weapon_pts = ValueBar(16, False)
    weapon_pts.set_property('value', 10)

    combat_pts = ValueBar(16, False)
    combat_pts.set_property('value', 15)

    table.attach(skill_pts, 1, 2, 0, 1)
    table.attach(weapon_pts, 1, 2, 1, 2)
    table.attach(combat_pts, 1, 2, 2, 3)

    return (skill_pts, combat_pts, weapon_pts)

def init_magic_value_bar(container):
    magic_pts = ValueBar(16, False)
    magic_pts.set_property('value', 2)
    container.add(magic_pts)

    return magic_pts

# inicializa tags de formatacao de texto -------------------------------------
def init_text_tags(tag_table):
    tag = gtk.TextTag('title')
    tag.set_property('pixels-below-lines', 4)
    tag.set_property('font', 'sans bold 16')
    tag.set_property('justification', gtk.JUSTIFY_CENTER)
    tag_table.add(tag)

    tag = gtk.TextTag('sub-title')
    tag.set_property('pixels-below-lines', 4)
    tag.set_property('font', 'sans bold 12')
    tag_table.add(tag)

    tag = gtk.TextTag('table-title')
    tag.set_property('weight', pango.WEIGHT_BOLD)
    tag.set_property('font', 'mono bold 10')
    tag_table.add(tag)

    tag = gtk.TextTag('table-body')
    tag.set_property('font', 'mono 10')
    tag_table.add(tag)

    tag = gtk.TextTag('bold')
    tag.set_property('weight', pango.WEIGHT_BOLD)
    tag_table.add(tag)


# Manipulacao da aparencia fisica do personagem ------------------------------
def draw_silhouette(image_widget, height, weight, race):
    body_pixbuf = body_pixbufs['human']

    '''
    scale = min(image_widget.allocation.width / \
                float(body_pixbufs['human'].get_width()), \
                image_widget.allocation.height / \
                float(body_pixbufs['human'].get_height()))

    width = body_pixbufs['human'].get_width() * scale
    height = body_pixbufs['human'].get_height() * \
             scale * (height / self.max_size)
    '''

    pixbuf = body_pixbuf.scale_simple(width, height, gtk.gdk.INTERP_NEAREST)
    image_widget.set_from_pixbuf(pixbuf)


# MessageDialog --------------------------------------------------------------
def message(parent, message, msg_type=gtk.MESSAGE_WARNING):
    msg = gtk.MessageDialog(parent,
                            gtk.DIALOG_DESTROY_WITH_PARENT,
                            msg_type, gtk.BUTTONS_CLOSE,
                            message)
    msg.run()
    msg.destroy()

